<template>
  <div class='pages-details'>
    <!---------------操作框-------------------------------------------------------------------------------------------------------->
    <div class="tableSearch">
      <el-button @click="openDialog(2)" size="mini" type="primary">返回</el-button>
    </div>
    <!---------------表单----------------------------------------------------------------------------------------------------------->
    <el-form :model="formData" :rules="ruleFormData" class="demo-ruleForm" label-width="120px" ref="dataForm"
             size="small">
      <el-row>
        <el-col :span='10'>
          <el-form-item label="课程标题：" prop="title">
            <el-input maxlength="32" placeholder="32字以内" v-model="formData.title" clearable
                      :disabled='handle == "see"'></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span='10'>
          <el-form-item label="列表内容：" prop="subTitle">
            <el-input maxlength="16" placeholder="16字以内" v-model="formData.subTitle" :disabled='handle == "see"'
                      clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="封面：" prop="imgUrl">
          <div class='imgWrap'>
            <div class='imgItem'>
              <p class='tips'>大图：上传图片的尺寸<span v-if='formData.dataType == 0'>{{wImgUrl}}px * {{hImgUrl}}px</span><span
                v-if='formData.dataType == 2'>{{wAudioImgUrl}}px * {{hAudioImgUrl}}px</span>，<br/>格式png，jpeg，jpg，gif。
              </p>
              <div class="imgbox"><img :src="formData.imgUrl" alt=""></div>
              <div class='loadWrap' v-if='handle != "see"'>
                <el-upload :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile" :show-file-list="false"
                           action="1" class="upload-demo">
                  <el-button :disabled="false" @click="addindex('imgUrl')" size="mini" type="primary">点击上传</el-button>
                </el-upload>
                <el-form-item>
                  <el-button :disabled="false" @click="deleteImg('imgUrl')" key='imgUrl' size="mini" type="danger">删 除
                  </el-button>
                </el-form-item>
              </div>
            </div>
            <div class='imgItem'>
              <p class='tips'>小图：上传图片的尺寸{{wSimgUrl}}px * {{hSimgUrl}}px，<br/>格式png，jpeg，jpg，gif。</p>
              <div class="imgbox"><img :src="formData.sImgUrl" alt=""></div>
              <div class='loadWrap' v-if='handle != "see"'>
                <el-upload :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile" :show-file-list="false"
                           action="1" class="upload-demo">
                  <el-button :disabled="false" @click="addindex('sImgUrl')" size="mini" type="primary">点击上传</el-button>
                </el-upload>
                <el-form-item>
                  <el-button :disabled="false" @click="deleteImg('sImgUrl')" key='sImgUrl' size="mini" type="danger">删 除
                  </el-button>
                </el-form-item>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span='10'>
          <el-form-item label="课程分类：" prop="courseType">
            <el-select placeholder="请选择" size="small" v-model="formData.courseType" :disabled='handle == "see"'>
              <el-option :key="'courseType'+item.id" :label="item.name" :value="item.id" v-for="item in courseTypeList">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span='10'>
          <el-form-item label="课程类型：" prop="dataType">
            <el-radio-group v-model="formData.dataType" @change='radioChange($event)' :disabled='handle == "see"'>
              <el-radio :key='"dataType"+item.id' :label="item.id" v-for='item in dataTypeList'>{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if='formData.dataType != 0'>
        <el-col>
          <el-form-item class='course-price' label="课程价格：" prop="price" key='coursePrice'>
            <strong>¥</strong>
            <el-input maxlength="32" v-model="formData.price" clearable :disabled='handle == "see"'
                      @keyup.native='replace(formData,"price")' style='width: 175px'></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label='课程介绍' prop="content" v-if='formData.dataType == 2'>
            <div class='course-des-imgs'>
              <div class='course-des-imgs-item'>
                <div v-for='(item, index) in formData.content' @mouseenter="activeItem = index" @mouseleave="activeItem = null"><img :src="item">
                  <transition name="el-zoom-in-center">
                    <span v-show='activeItem == index'>
                      <i class='el-icon-arrow-left' v-if='index != 0' @click='moveto(index, -1)'></i>
                      <i class='el-icon-arrow-right' v-if='index != formData.content.length-1' @click='moveto(index, 1)'></i>
                      <i class='el-icon-delete' @click='delCourseDesImg(index)'></i></span>
                  </transition>
                </div>
              </div>
            </div>
            <div class="loadWrap">
              <el-upload v-if='handle != "see"' :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile" :show-file-list="false"
                         action="1" class="upload-demo" style='margin-right: 15px'>
                <el-button @click="addindex('imgUrlList')" size="small" type="primary">点击上传</el-button>
              </el-upload>
              <el-button type="primary" plain @click='previewBtn(formData.content, true)'>预 览</el-button>
            </div>
          </el-form-item>
          <el-form-item v-else label="课程内容" prop="content" style='width: 870px' key='courseContent'>
            <div class="content-see" v-if='handle == "see"'>
              <div class='content-container-menus'>
                <el-button type="info" plain size='mini' @click='previewBtn(formData.content)'
                           style='margin-left: 15px'>预览
                </el-button>
              </div>
              <div class='content-container'>
                <div class='content-container-box' v-html='formData.content'></div>
              </div>
            </div>
            <div v-else-if='handle == "new" || isFinished' class='editor-container'>
              <wangeditor :catchContent.sync="formData.content" @clearValidate='clearValidate("content")'
                          :albumsLen="formData.albums.length"></wangeditor>
              <el-button type="info" plain size='mini' @click='previewBtn(formData.content)' style='margin-left: 15px'>
                预览
              </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <!------------专辑-------------------------------------------------------------------------------------------------------->
      <div class='audio-lists' v-if='formData.dataType == 2'>
        <el-form-item class='course-price' label="音频条数" v-if='formData.albums.length>0'>
          <span class='audio-num'>{{formData.albums.length}}</span>
          <el-button icon='el-icon-plus' key='addaudio' size='mini' type="primary" @click='addAudio'
                     v-if='handle != "see"'>增加
          </el-button>
        </el-form-item>
        <el-row>
          <el-col :span='15' class='audio-lists-group'>
            <div class='audio-lists-item' v-for='(item, key) in formData.albums' :key='"album"+key'>
              <div class='audio-lists-dele' v-if='formData.albums.length > 1'>
                <strong>{{key+1}}</strong>
                <i class='el-icon-delete' v-if='handle != "see"' @click='deleAudio(key)'></i>
              </div>
              <el-row style='padding-top: 10px'>
                <el-col :span='18'>
                  <el-form-item class='course-price' label="音频标题：" :prop="'albums.' + key +'.title'"
                                :rules='ruleFormData.title'>
                    <el-input maxlength="32" v-model="item.title" clearable :disabled='handle == "see"'></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-collapse-transition>
                <div v-show='!item.isHidden'>
                  <el-row>
                    <el-col :span='18'>
                      <el-form-item class='course-price' label="添加音频：" :prop="'albums.' + key +'.soundName'"
                                    :rules='ruleFormData.soundUrl'>
                        <el-input placeholder='上传本地音频文件或输入音频URL地址' v-model="item.soundName" clearable
                                  :disabled='handle == "see" || item.hasLoadAudio'></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span='6' style='display: flex;justify-content: flex-start' v-if='handle != "see"'>
                      <el-form-item label-width='15px'>
                        <el-upload :before-upload="beforeAvatarUploadAudio" :http-request="uploadSectionAudio"
                                   :show-file-list="false"
                                   action="1" class="upload-demo">
                          <el-button key='selectfile' size='mini' type="primary" @click="addindex(key)">选择文件</el-button>
                        </el-upload>
                      </el-form-item>
                      <el-form-item label-width='15px'>
                        <el-button @click='resetSoundUrl(key)' key='reset' size='mini' type="danger">重置</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item v-if='handle != "see"'>
                    <p class='tips'>格式支持mp3、wav、m4a，语音时长不超过30分钟</p>
                  </el-form-item>
                  <el-form-item label="音频文字：" prop="content" style='width: 800px'
                                :prop="'albums.' + key +'.content'" :rules='ruleFormData.audioContent'>
                    <div class="content-see" v-if='handle == "see"'>
                      <div class='content-container-menus'>
                        <el-button type="info" plain size='mini' @click='previewBtn(item.content)'
                                   style='margin-left: 15px'>预览
                        </el-button>
                      </div>
                      <div class='content-container'>
                        <div class='content-container-box' v-html='item.content'></div>
                      </div>
                    </div>
                    <div v-else class='editor-container'>
                      <wangeditor :catchContent.sync="item.content" :albumsLen="formData.albums.length"
                                  :hideImg="true"></wangeditor>
                      <el-button type="info" plain size='mini' @click='previewBtn(item.content)'
                                 style='margin-left: 15px'>预览
                      </el-button>
                    </div>
                  </el-form-item>
                  <el-form-item label="" label-width='30px'>
                    <el-radio-group v-model="item.isFree" :disabled='handle == "see"'>
                      <el-radio :label=1>免费试听</el-radio>
                      <el-radio :label=0>付费</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-collapse-transition>
              <el-form-item style='text-align: right;padding-right: 30px' v-if='formData.albums.length > 1'>
                <el-button @click='contentMore(key)' type="text">{{item.isHidden ? '更多' : '收起'}}<i
                  class="el-icon-d-arrow-right el-icon--right"></i></el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-row v-if='handle != "see"'>
        <el-col>
          <div class='footer'>
            <el-button @click='saveFormData(0)' key='save' plain type="primary">保 存</el-button>
            <el-button @click='saveFormData(1)' key='release' type="primary">发 布</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <!-------------------弹框----------------------------------------------------------------------------------------->
    <el-dialog :show-close='false' :title="dialogType == 1 ? '确认发布' : '确认关闭'" :visible.sync="dialogVisible" center
               width="500px">
      <el-form label-width='80px' :model='priorityModel' :rules='rulePriorityModel' class="demo-ruleForm"
               ref="ratingPriority">
        <template v-if='dialogType == 1'>
          <el-form-item label='设置权重' prop='priorityRating'>
            <el-input maxlength='5' placeholder='请输入权重值' v-model='priorityModel.priorityRating'
                      @keyup.native='replace(priorityModel,"priorityRating")' clearable></el-input>
          </el-form-item>
          <el-form-item label=''>
            <p class='tips'>权重值越大，排序越靠前，权重值为正整数，可输入范围：0—10000</p>
          </el-form-item>
        </template>
        <el-form-item label='' label-width='0px' v-else>
          <h4 style='text-align: center'>您确认要离开该页面吗，您输入的数据可能不会被保存？</h4>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
            <el-button @click="closedialog">取消</el-button>
            <el-button @click="confirmdialog" type="primary">{{dialogType == 1 ? '发布' : '确定'}}</el-button>
          </span>
    </el-dialog>
    <!-------------------预览弹框----------------------------------------------------------------------------------------->
    <el-dialog title="预览" :visible.sync="dialogPreviewVisible" width="375px" class='preview-dialog'>
      <div class='preview-container'>
        <template v-if='isCourseDes'>
          <img v-for='item in formData.content' :src="item">
        </template>
        <div v-else v-html='previewHtml'></div>
      </div>
    </el-dialog>
    <!--------------------audio获取时长---------------------------------------------------------------------------------->
    <audio :src='audioUrl' style='display: none' id='audioModel' :key='audioKey'></audio>
  </div>
</template>

<script>
  import util from '@/util'
  import {mapState} from "vuex";
  import wangeditor from './wangeditor/index'
  import {
    uploadFile,
    getFile,
    newCourse,
    coursetype,
    release,
    courseInfo,
    updCourse,
    getvideoFile
  } from "@/api";

  export default {
    name: "onlineClassroom-details",
    data() {
      const checkImgUrl = (rule, value, callback) => {
        if (this.formData.sImgUrl == '') {
          return callback(new Error('请上传封面小图'));
        } else {
          callback();
        }
      };
      const checkPriorityRating = (rule, value, callback) => {
        if (+value > 10000) {
          return callback(new Error('超过输入范围'));
        } else {
          callback();
        }
      };
      const checkPrice = (rule, value, callback) => {
        if (!util.validFloatNumber(value)) {
          return callback(new Error('此处只能输入数字或者小数点'));
        } else {
          callback();
        }
      };
      return {
        operateStatus: 0, //0 保存  1发布
        imgIndex: '', //图片key
        dialogType: 1, //1确认发布  2 确认关闭
        dialogVisible: false, //弹框
        dialogPreviewVisible: false, // 预览弹框
        previewHtml: '', // 预览内容
        handle: '',
        targetId: '', //课程id
        isFinished: false, //查看详情时数据是否加载完成
        wImgUrl: 702, //图片尺寸宽
        hImgUrl: 260, //图片尺寸高
        wAudioImgUrl: 750, //图片尺寸宽专辑
        hAudioImgUrl: 478, //图片尺寸高专辑
        wSimgUrl: 220, //小图片尺寸宽
        hSimgUrl: 162, //小图片尺寸高
        dataTypeList: [{
          name: '图文',
          id: 0
        }, {
          name: '专辑',
          id: 2
        }], //内容种类列表
        priorityModel: {
          priorityRating: null, //权重
        },
        rulePriorityModel: {
          priorityRating: [{required: true, message: '请输入权重', trigger: 'blur'},
            {validator: checkPriorityRating, trigger: 'blur'}]
        },
        audioUrl: '', //通过audio获取音频时长
        addItem: {
          title: '',
          soundUrl: '',  //音频url
          soundLen: '',  //音频时长，单位:秒
          content: '',
          isFree: 1,    //是否付费 1-免费 0-付费
          soundName: '', //音频名字
          isHidden: false, //收起或者下拉
          hasLoadAudio: false //音频地址框是否禁用
        },
        //图文数据
        imgTxtData: {
          id: '',
          title: '',      //课程标题
          subTitle: '',
          imgUrl: '',     //课程大图url
          sImgUrl: '',    //课程小图url
          courseType: '', //课程分类
          dataType: 0,   //课程类型  0-图文 1-音频 2-专辑
          content: '',    //课程内容
          price: '',
          albums: [], //专辑列表 dataType=1或2时传入
        },
        //专辑数据
        audioData: {
          id: '',
          title: '',      //课程标题
          subTitle: '',
          imgUrl: '',     //课程大图url
          sImgUrl: '',    //课程小图url
          courseType: '', //课程分类
          dataType: 2,   //课程类型  0-图文 1-音频 2-专辑
          content: [],    //课程内容
          price: '',
          albums: [], //专辑列表 dataType=1或2时传入
        },
        formData: {
          id: '',
          title: '',      //课程标题
          subTitle: '',
          imgUrl: '',     //课程大图url
          sImgUrl: '',    //课程小图url
          courseType: '', //课程分类
          dataType: 0,   //课程类型  0-图文 1-音频 2-专辑
          content: '',    //课程介绍/课程内容
          price: '',
          albums: [], //专辑列表 dataType=1或2时传入
        },
        ruleFormData: {
          title: [{required: true, message: '请输入标题', trigger: 'blur'}],
          subTitle: [{required: true, message: '请输入列表内容', trigger: 'blur'}],
          imgUrl: [{required: true, message: '请上传封面大图', trigger: 'change'},
            {validator: checkImgUrl, trigger: 'change'}],
          courseType: [{required: true, message: '请选择课程分类', trigger: 'change'}],
          content: [{required: true, message: '此处不能为空', trigger: 'change'}],
          price: [{required: true, message: '请输入课程价格', trigger: 'blur'},
            {validator: checkPrice, trigger: 'blur'}
          ],
          soundUrl: [{required: true, message: '请上传音频文件', trigger: 'blur'}],
          audioContent: [{required: true, message: '请输入音频文字', trigger: 'change'}]
        },
        courseTypeList: [], //课程分类列表
        audioKey: 'audio', //audio标签key
        isCourseDes: false, //是否课程介绍（预览时）
        activeItem: null, // mouseenter事件
      }
    },
    components: {
      wangeditor
    },
    computed: mapState([
      "sub",
      "power",
      "merchantId"
    ]),
    created() {
      this.getCourseType()
      this.handle = util.getQuery('handle')
      if (this.handle != 'new') {
        this.targetId = util.getQuery('targetId')
        this.getDetails()
      }
    },
    mounted() {},
    methods: {
      //获取课程列表-----------------------------接口-----------------------
      getCourseType() {
        coursetype().then(res => {
          if (res.code == 200) {
            this.courseTypeList = res.data
          }
        })
      },
      //新增课程
      saveFormData(status) {
        let that = this
        switch (status) {
          //发布
          case 1:
            this.$refs.dataForm.validate((valid) => {
              if (valid) {
                this.openDialog(status)
              } else {
                this.tipsBox('请检查必填信息是否填写完整！', 'error')
              }
            })
            break;
          //保存
          case 0:
            that.setSoundLen().then(function () {
              let data = JSON.parse(JSON.stringify(that.formData))
              if (that.targetId) {
                updCourse(data).then(res => {
                  if (res.code == 200) {
                    that.tipsBox('修改成功', 'success')
                    that.routerPush(status)
                  } else {
                    that.tipsBox(res.msg, 'error')
                  }
                })
              } else {
                data.companyId = that.merchantId
                newCourse(data).then(res => {
                  if (res.code == 200) {
                    that.tipsBox('保存成功', 'success')
                    that.routerPush(status)
                  } else {
                    that.tipsBox(res.msg, 'error')
                  }
                })
              }
            })
            break
        }
      },
      //获取音频时长 --- h5不支持amr、wma格式音频
      getItem(soundUrl, index) {
        let that = this
        this.audioKey = 'audio' + index
        this.audioUrl = soundUrl
        return new Promise(function (resolve, reject) {
          that.$nextTick(function () {
            let dom = document.getElementById('audioModel')
            dom.oncanplaythrough = function () {
              let time = Math.floor(dom.duration).toString()
              resolve(time)
            }
          })
        })
      },
      async setSoundLen() {
        let that = this
        let arr = this.formData.albums
        for (let [i, item] of new Map(arr.map((item, i) => [i, item]))) {
          if (item.soundName == '') {
            that.$set(item, "soundUrl", '')
          } else if (item.soundName != '' && item.soundUrl == '') {
            that.$set(item, "soundUrl", item.soundName)
          }
          if (!item.soundLen) {
            let result = await that.getItem(item.soundUrl, i)
            that.$set(item, "soundLen", result)
          }
        }
      },
      //发布课程
      confirmdialog() {
        let that = this
        //发布
        if (this.dialogType == 1) {
          this.$refs.ratingPriority.validate((valid) => {
            if (valid) {
              /*-------获取音频时长----------*/
              that.setSoundLen().then(function () {
                let data1 = JSON.parse(JSON.stringify(that.formData))
                if (that.targetId) {
                  updCourse(data1).then(resupd => {
                    if (resupd.code == 200) {
                      let data = {
                        id: data1.id,
                        priorityRating: that.priorityModel.priorityRating
                      }
                      that.released(data)
                    } else {
                      that.tipsBox(resupd.msg, 'error')
                    }
                  })
                } else {
                  data1.companyId = that.merchantId
                  newCourse(data1).then(res => {
                    if (res.code == 200) {
                      let data = {
                        id: res.data.id,
                        priorityRating: that.priorityModel.priorityRating
                      }
                      that.released(data)
                    } else {
                      that.tipsBox(res.msg, 'error')
                    }
                  })
                }
              })
            }
          })
        } else {
          //返回
          this.back();
        }
      },
      //发布
      released(data) {
        release(data).then(res => {
          if (res.code == 200) {
            this.tipsBox('发布成功', 'success')
            this.routerPush(1);
          } else {
            this.tipsBox(res.msg, 'error')
          }
        })
      },
      //获取详情
      getDetails() {
        courseInfo(this.targetId).then(res => {
          if (res.code == 200) {
            let datas = res.data
            let album = datas.albums
            if(datas.dataType == 2){
              if(datas.content.search(/\[/)>=0 && datas.content.search(/\]/)>=0){
                datas.content = JSON.parse(datas.content)
              } else {
                datas.content = []
              }
            }
            for (let i = 0; i < album.length; i++) {
              if (album.length > 1) {
                datas.albums[i].isHidden = true
              }
              if (datas.albums[i].soundUrl == datas.albums[i].soundName) {
                datas.albums[i].hasLoadAudio = false
              } else {
                datas.albums[i].hasLoadAudio = true
              }
            }
            this.$nextTick(function () {
              this.formData = datas
              this.isFinished = true
            })
          } else {
            this.tipsBox(res.msg, 'error')
          }
        })
      },
      /*----------------------------------图片/音频上传----------------------------------------*/
      //添加图片
      addindex(key) {
        this.imgIndex = key
      },
      //删除图片
      deleteImg(key) {
        this.formData[key] = '';
      },
      //删除课程介绍图片
      delCourseDesImg(index) {
        this.formData.content.splice(index, 1)
      },
      //音频格式
      beforeAvatarUploadAudio(file) {
        console.log(file);
        const isAudio =
          file.type.search(/mp3/) > 0 ||
          file.type.search(/wav/) > 0 ||
          file.type.search(/m4a/) > 0 ||
          file.name.search(/.mp3/) > 0 ||
          file.name.search(/.wav/) > 0 ||
          file.name.search(/.m4a/) > 0

        // const is30M = file.size / 1024 / 1024 <= 30;
        if (!isAudio) {
          this.$message.error("上传文件格式错误!");
          return false;
        }
        // if (!is30M) {
        //   this.$message.error("文件不超过30M!");
        //   return false;
        // }
        return isAudio;
      },
      //图片大小格式
      beforeAvatarUpload(file) {
        let that = this
        const isJPG =
          file.type === "image/png" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg" ||
          file.type === "image/gif";
        let width, height, isSize

        if (!isJPG) {
          this.$message.error("上传图片格式错误!");
          return false
        }
        if (that.imgIndex == 'imgUrlList') {
          isSize = true
        } else {
          isSize = new Promise(function (resolve, reject) {
            //图文
            if (that.formData.dataType == 0 && that.imgIndex == 'imgUrl') {
              width = that.wImgUrl
              height = that.hImgUrl
            }
            //专辑
            if (that.formData.dataType == 2 && that.imgIndex == 'imgUrl') {
              width = that.wAudioImgUrl
              height = that.hAudioImgUrl
            }
            if (that.imgIndex == 'sImgUrl') {
              width = that.wSimgUrl
              height = that.hSimgUrl
            }

            let _URL = window.URL || window.webkitURL;
            let img = new Image();
            img.onload = function () {
              let valid = img.width == width && img.height == height;
              valid ? resolve() : reject();
            }
            img.src = _URL.createObjectURL(file);
          }).then(() => {
            return true
          }, () => {
            this.$message.error(`上传的图片必须是${width}px * ${height}px`)
            return Promise.reject();
          });
        }
        return isJPG && isSize;
      },
      //上传
      uploadSectionFile(param) {
        var fileObj = param.file;
        var data = new FormData();
        data.append("projectName", fileObj.name);
        data.append("file", fileObj);
        uploadFile(data).then(res => {
          if (res.code == 200) {
            let a = `${getFile}?id=${res.data.id}`;
            switch (this.imgIndex) {
              case "imgUrl":
                this.formData.imgUrl = a;
                break;
              case "sImgUrl":
                this.formData.sImgUrl = a;
                break;
              case "imgUrlList":
                this.formData.content.push(a);
                break;
            }
          } else {
            this.tipsBox(res.msg, 'error')
          }
        });
      },
      //上传音频
      uploadSectionAudio(param) {
        let that = this
        var fileObj = param.file;
        var data = new FormData();
        data.append("projectName", fileObj.name);
        data.append("file", fileObj);
        uploadFile(data).then(res => {
          if (res.code == 200) {
            // let a = `${getFile}?id=${res.data.id}`;
            this.$set(this.formData.albums[this.imgIndex], 'soundName', fileObj.name)
            getvideoFile({
              id: res.data.id,
              returnUrlFlag: 1
            }).then(res => {
              this.formData.albums[this.imgIndex].soundUrl = res
              this.formData.albums[this.imgIndex].hasLoadAudio = true
            })
          } else {
            this.tipsBox(res.msg, 'error')
          }
        });
      },
      //删除图片
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      //预览大图
      pictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      /* ---------------------------------------页面操作--------------------------------------*/
      //图片列表左右移动
      moveto(index, type) {
        let arr = JSON.parse(JSON.stringify(this.formData.content))
        if(type > 0){
          this.formData.content = this.swapItems (arr, index, index+1)
        }else {
          this.formData.content = this.swapItems (arr, index, index-1)
        }
      },
      swapItems (arr, index1, index2){
        arr[index1] = arr.splice(index2, 1, arr[index1])[0]
        return arr
      },
      //查看更多
      contentMore(index) {
        let boo = !this.formData.albums[index].isHidden
        this.$set(this.formData.albums[index], 'isHidden', boo)
      },
      //课程类型切换
      radioChange(val) {
        switch (val) {
          //专辑 -> 图文
          case 0:
            this.audioData = JSON.parse(JSON.stringify(this.formData))
            this.audioData.dataType = 2          //2 专辑类型
            this.formData = JSON.parse(JSON.stringify(this.imgTxtData))
            break;
          //图文 -> 专辑
          case 2:
            this.imgTxtData = JSON.parse(JSON.stringify(this.formData))
            this.imgTxtData.dataType = 0        //0 图文类型
            this.formData = JSON.parse(JSON.stringify(this.audioData))
            if (this.formData.albums.length < 1) {
              this.addAudio()
            }
            break;
        }
        if (this.formData.id == '' && this.handle == 'edit') {
          this.formData.id = this.audioData.id == '' ? this.imgTxtData.id : this.audioData.id
        }
        this.$nextTick(function () {
          this.$refs.dataForm.clearValidate()
        })
      },
      //重置音频url
      resetSoundUrl(index) {
        this.$set(this.formData.albums[index], 'soundName', '')
        this.formData.albums[index].soundUrl = ''
        this.formData.albums[index].hasLoadAudio = false
      },
      //增加专辑
      addAudio() {
        this.formData.albums.push(JSON.parse(JSON.stringify(this.addItem)))
      },
      //清除验证提示
      clearValidate(item = '') {
        this.$refs['dataForm'].clearValidate([item])
      },
      // 关闭弹框
      closedialog() {
        this.dialogVisible = false
        if (this.dialogType == 1) {
          this.priorityModel.priorityRating = null
        }
      },
      // 打开弹框
      openDialog(status) {
        if (this.handle == 'see') {
          this.back();
        }
        this.dialogType = status
        this.dialogVisible = true
      },
      //删除音频
      deleAudio(index) {
        this.formData.albums.splice(index, 1)
        if (this.formData.albums.length < 2) {
          this.formData.albums[0].isHidden = false
        }
      },
      //字符串过滤
      replace(obj, key) {
        let that = this
        let event = event || window.event
        if (event.keyCode == 13) {
          setTimeout(() => {
            that.validItem(obj, key);
          }, 100);
        } else {
          that.validItem(obj, key);
        }
      },
      validItem(obj, key) {
        let res = ''
        switch (key) {
          case 'priorityRating':
            res = util.replaceNumber(obj[key]);
            break;
          case 'price':
            res = util.replaceNum(obj[key], 6);
            break;
        }
        this.$set(obj, key, res);
      },
      //路由跳转列表页
      routerPush(status) {
        util.routerTo('/app-management/online-classroom/onlineClassroom-list', {
          status: status,
        })
        this.$store.commit("SET_ISRELOADDATA", true);
        return;
      },
      //预览弹框
      previewBtn(html, isCourseDes = false) {
        this.isCourseDes = isCourseDes
        this.dialogPreviewVisible = true
        this.previewHtml = html
      },
      //提示框
      tipsBox(txt, type) {
        this.$message({
          message: txt,
          type: type
        });
      },
      back() {
        util.routerTo('/app-management/online-classroom/onlineClassroom-list');
        return;
      }
    }
  }
</script>

<style lang='less' scoped>
  .pages-details {
    min-width: 800px;

    .tips {
      color: darkgray;
      line-height: 20px;
    }

    .imgWrap {
      display: flex;
      justify-content: flex-start;

      .imgItem {
        &:nth-child(2) {
          margin-left: 20px;
        }
      }

      .imgbox {
        min-width: 150px;
        height: 150px;
        border: 1px dashed #dcdfe6;
        margin: 15px 0;
        display: inline-block;

        img {
          display: block;
          width: auto;
          height: 100%;
          margin: 0 auto;
        }
      }
    }

    .loadWrap {
      display: flex;
      justify-content: flex-start;

      .upload-demo {
        margin-right: 15px;
      }
    }

    .footer {
      text-align: center;
      width: 900px;
      margin-top: 20px;
      padding: 30px 0 100px;
    }

    .course-price {
      strong {
        margin-right: 10px;
      }
    }

    .course-des-imgs {
      border: 1px dashed #dcdfe6;
      height: 200px;
      display: inline-block;
      min-width: 200px;
      max-width: 800px;
      overflow-y: hidden;
      overflow-x: scroll;

      .course-des-imgs-item {
        height: 100%;
        display: flex;
        justify-content: start;
        div {
          position: relative;
          margin-right: 5px;
          height: 100%;

          &:last-child {
            margin-right: 0px;
          }

          img {
            display: block;
            height: 100%;
          }

          span {
            position: absolute;
            background: rgba(0, 0, 0, .7);
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;

            i {
              display: block;
              width: 50px;
              height: 50px;
              font-size: 30px;
              color: #fff;
              cursor: pointer;
              text-align: center;
              line-height: 50px;
            }
          }
        }
      }
    }

    .audio-lists {
      padding-top: 15px;

      .audio-num {
        font-weight: bold;
        margin-right: 20px;
        border: 1px solid #dcdfe6;
        width: 80px;
        text-align: center;
      }

      .audio-lists-group {
        min-width: 900px;
        margin-left: 40px;

        .audio-lists-item {
          margin-bottom: 20px;
          padding-top: 20px;
          background-color: #fff;
          border: 1px dashed #dcdfe6;
          border-radius: 4px;
        }
      }

      .audio-lists-dele {
        display: flex;
        justify-content: space-between;
        padding: 0 25px 10px;

        strong {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          text-align: center;
          line-height: 30px;
          background: #dcdfe6;
        }

        .el-icon-delete {
          &:before {
            font-size: 24px;
            color: #F56C6C;
            cursor: pointer;
          }
        }
      }
    }

    .content-see {
      width: 680px;
      border: 1px solid #ccc;

      .content-container-menus {
        height: 44px;
        text-align: right;
        background-color: #f1f1f1;
        padding: 4px 10px 0 0;
        box-sizing: border-box;
        border-bottom: 1px solid #ccc;
      }
    }

    .content-container {
      width: 100%;
      height: 300px;
      box-sizing: border-box;
      padding: 0 15px;
      overflow-x: hidden;
      overflow-y: scroll;

      .content-container-box {
        width: 100%;
        height: auto;
      }
    }

    .editor-container {
      position: relative;

      .el-button {
        position: absolute;
        right: 10px;
        top: 8px;
      }
    }

    .preview-dialog {
      .preview-container {
        overflow-x: hidden;
        overflow-y: scroll;
        height: 600px;
        width: 375px;
        margin: -15px -20px;
        padding: 0px 15px;
        box-sizing: border-box;
        img{
          display: block;
          width: 100%;
        }
      }
    }
  }
</style>
<style scoped>
  .preview-container div >>> img {
    display: block !important;
  }
</style>
<style lang='less'>
  .pages-details {
    .el-dialog__header {
      background: #409EFF;

      .el-dialog__title {
        color: #fff;
      }
    }

    .el-dialog__wrapper {
      z-index: 20000 !important;

      .el-dialog__body {
        width: 410px;
      }
    }

    .course-price {
      .el-form-item__content {
        display: flex;
        justify-content: flex-start;
      }
    }

    .preview-dialog {
      .el-dialog__header {
        border-top-right-radius: 30px;
        border-top-left-radius: 30px;
      }

      .el-dialog {
        border-radius: 30px;

        .el-icon {
          color: #fff;
        }
      }
    }
  }

  .el-select-dropdown {
    z-index: 20000 !important;
  }
</style>
